package com.szh.cc.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szh.cc.entity.Order;
import com.szh.cc.mapper.OrderMapper;
import com.szh.cc.service.OrderService;
import com.szh.zh.feign.AccountClient;
import com.szh.zh.feign.StorageClient;
import feign.FeignException;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService, InitializingBean {

    @Resource
    private AccountClient accountClient;
    @Resource
    private StorageClient storageClient;


    @Override
    @GlobalTransactional
    public Long create(Order order) {
        order.setCreateDate(LocalDateTime.now());
        // 创建订单
        this.save(order);
        try {
            // 扣用户余额
            accountClient.deduct(order.getUserId(), order.getMoney());
            // 扣库存
            storageClient.deduct(order.getCommodityCode(), order.getCount());

        } catch (FeignException e) {
            log.error("下单失败，原因:{}", e.contentUTF8(), e);
            throw new RuntimeException(e.contentUTF8(), e);
        }
        return order.getId();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        
    }
}
